﻿// -----------------------------------------------------------------------
// <copyright file="SolutionEntity.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace hardvinyp.xrm
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Crm.Sdk.Messages;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class SolutionEntity
    {
        private TConexion parametroscon;

        public SolutionEntity(TConexion ParametrosConexion)
        {
            parametroscon = ParametrosConexion;
        }


        public List<TESolution> ListarSoluciones()
        {
            QueryExpression query = new QueryExpression("solution");
            query.ColumnSet = new ColumnSet(true);

            CrmDataAccess cda = new CrmDataAccess(parametroscon);

            EntityCollection ecole = cda.RetrieveMultiple(query);

            if (ecole.Entities.Count > 0)
            {
                List<TESolution> listasoluciones = new List<TESolution>();

                foreach (Entity ent in ecole.Entities)
                {
                    if (ent["uniquename"].ToString() != "System" && ent["uniquename"].ToString() != "Active"
                        && ent["uniquename"].ToString() != "Basic" && ent["uniquename"].ToString() != "ActivityFeeds")
                    {
                        Guid idsol = new Guid(ent.Attributes["solutionid"].ToString());
                        listasoluciones.Add(
                            new TESolution
                                {
                                    Idsolution = idsol,
                                    Nombre = ent.Attributes["uniquename"].ToString()
                                });
                    }
                }
                            return listasoluciones;
            }
            else
            {
                throw new Exception("Ha ocurrido un error inesperado: El ambiente que ha seleccionado no contiene soluciones");
            }

        }

        public byte[] exportarsolucion(TESolution solucion, bool administrada)
        {
            ExportSolutionRequest expsolreq = new ExportSolutionRequest();
            expsolreq.Managed = administrada;
            expsolreq.SolutionName = solucion.Nombre;

            CrmDataAccess cda = new CrmDataAccess(parametroscon);

            ExportSolutionResponse expsolres = (ExportSolutionResponse)cda.ExecuteorganizationRequest(expsolreq);
            byte[] exportXml = expsolres.ExportSolutionFile;

            return exportXml;
        }
    }
}
